package com.jtjrenren.android.taxi.passenger.manger.pay.weixin;

import android.app.Activity;

import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.bean.event.PayEvent;
import com.jtjrenren.android.taxi.passenger.utils.ModuleUtils;

import org.greenrobot.eventbus.EventBus;

import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2016/3/18.
 */
public class WxPayManger {
    private IWXAPI api;

    private PayReq req;

    public void initManger(Activity activity) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(activity, ModuleUtils.getStrFromResource(R.string.wx_app_id));
            api.registerApp(ModuleUtils.getStrFromResource(R.string.wx_app_id));
            req = new PayReq();
        }
    }
    /**
     * 发起支付 如果不支持直接返回false
     *
     * @return
     */
    public boolean pay2(final String prepay_id) {
        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();

        if (!sIsWXAppInstalledAndSupported) {
            return false;
        }

        new Thread() {
            @Override
            public void run() {
                genPayReq(prepay_id);
                EventBus.getDefault().post(new PayEvent(PayEvent.MODE_THRIDPAY_START));
                api.sendReq(req);
            }
        }.start();

        return true;
    }

    /**
     * 生成请求参数
     *
     * @param prepay_id
     */
    private void genPayReq(String prepay_id) {
        req.appId = ModuleUtils.getStrFromResource(R.string.wx_app_id);
        req.partnerId = ModuleUtils.getStrFromResource(R.string.wx_mch_id);
        req.prepayId = prepay_id;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(ModuleUtils.getStrFromResource(R.string.wx_api_key));

        String appSign = MD5.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();
        return appSign;
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 随机字符串，不长于32位。
     *
     * @return
     */
    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
                .getBytes());
    }
}
